<?php

// +----------------------------------------------------------------------
// | 文件 WeixinSDK.class.php
// +----------------------------------------------------------------------
// | 说明 
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

class WeixinSDK extends Common\Util\ThinkSDK\ThinkOauth {

    /**
     * 获取requestCode的api接口
     * @var string
     */
    protected $GetRequestCodeURL = 'https://open.weixin.qq.com/connect/qrconnect';

    /**
     * 获取access_token的api接口
     * @var string
     */
    protected $GetAccessTokenURL = 'https://api.weixin.qq.com/sns/oauth2/access_token';

    /**
     * 获取request_code的额外参数,可在配置中修改 URL查询字符串格式
     * @var srting
     */
    protected $Authorize = 'scope=snsapi_login';

    /**
     * API根路径
     * @var string
     */
    protected $ApiBase = 'https://api.weixin.qq.com/';

    /**
     * 组装接口调用参数 并调用接口
     * @param  string $api    微博API
     * @param  string $param  调用API的额外参数
     * @param  string $method HTTP请求方法 默认为GET
     * @return json
     */
    public function call($api, $param = '', $method = 'GET', $multi = false) {
        /* 微信调用公共参数 */
        $params = array(
            'access_token' => $this->Token['access_token'],
            'openid' => $this->openid(),
        );
        $data = $this->http($this->url($api), $this->param($params, $param), $method);
        return json_decode($data, true);
    }

    public function parseExtend($request)
    {
        if ($request['access_token'] && $request['openid']){
            return [
                'access_token' => $request['access_token'],
                'openid' => $request['openid'],
                'nickname' => $request['nickname'],
                'avatar' => $request['avatar'],
            ];
        }else{
            return null;
        }
    }

    /**
     * 解析access_token方法请求后的返回值 
     * @param string $result 获取access_token的方法的返回值
     */
    protected function parseToken($result, $extend) {
        $data = json_decode($result, true);
        $extend && $data = array_merge($data, $extend);
        if ($data['access_token']) {
            $this->Token = $data;
            $data['openid']   = $this->openid();
            if (empty($data['nickname'])){
                $res = $this->http($this->url('sns/userinfo'), array('access_token' => $data['access_token'], 'openid' => $data['openid']));
                $this->UserInfo = json_decode($res, true);
                $data['nickname'] = $this->UserInfo['nickname'];
                $data['avatar']   = $this->UserInfo['headimgurl'];
            }
            return $data;
        } else
            throw new Exception("获取微信 ACCESS_TOKEN 出错：{$result}");
    }

    public function getAccessToken($code, $extend = null)
    {
        $this->config();
        $params = array(
                'appid'         => $this->AppKey,
                'secret'        => $this->AppSecret,
                'grant_type'    => $this->GrantType,
                'code'          => $code,
        );
        $data = $this->http($this->GetAccessTokenURL, $params, 'GET');
        $this->Token = $this->parseToken($data, $extend);
        return $this->Token;
    }

    public function getUnionid($access_token, $openid)
    {
        $params = [
            'access_token' => $access_token,
            'openid'       => $openid,
            'lang' => 'zh_CN'
        ];
        $data = $this->http('https://api.weixin.qq.com/sns/userinfo', $params, 'GET');
        $data = json_decode($data, true);
        return $data['unionid'];
    }

    /**
     * 获取当前授权应用的openid
     * @return string
     */
    public function openid() {
        return $this->Token['openid'];
    }

    public function nickname()
    {
        return $this->UserInfo['nickname'];
    }


    public function code($redirect_url, $state = '')
    {
        $redirect = U('Home/Sso/code', ['channel'=>'weixin', 'redirect_url' => base64_encode($redirect_url)], false, true);
        $redirect = urlencode($redirect);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->AppKey."&redirect_uri={$redirect}&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect";
    }

    public function share($param)
    {
        return ['type' => 'qrcode', 'url'  => $param['share_url']];
    }
}
